package com.gas.project.gas.grade.controller;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.gas.common.utils.DateUtils;
import com.gas.common.utils.StringUtils;
import com.gas.common.utils.poi.ExcelUtil;
import com.gas.framework.aspectj.lang.annotation.Log;
import com.gas.framework.aspectj.lang.enums.BusinessType;
import com.gas.framework.web.controller.BaseController;
import com.gas.framework.web.domain.AjaxResult;
import com.gas.framework.web.page.TableDataInfo;
import com.gas.project.gas.grade.domain.CourseValidGrade;
import com.gas.project.gas.message.domain.Message;
import com.gas.project.gas.message.service.IMessageService;
import com.gas.project.gas.resit.domain.CourseResit;
import com.gas.project.gas.student.domain.Student;
import com.gas.project.gas.student.service.IStudentService;
import com.gas.project.system.user.domain.User;
import com.gas.project.system.user.service.IUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.gas.project.gas.grade.domain.CourseGrade;
import com.gas.project.gas.grade.service.ICourseGradeService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 课程成绩Controller
 *
 * @author xyl
 * @date 2022-04-03
 */
@Controller
@RequestMapping("/gas/grade")
public class CourseGradeController extends BaseController {
    private String prefix = "gas/grade";

    @Autowired
    private ICourseGradeService courseGradeService;
    @Autowired
    private IStudentService studentService;
    @Autowired
    private IMessageService messageService;
    @Autowired
    private IUserService userService;

    @RequiresPermissions("gas:grade:view")
    @GetMapping()
    public String grade(ModelMap mmap) {
        User sysUser = getSysUser();
        if(sysUser.isStudent()){
            String content = "", grade = "";
            Student student = studentService.selectStudentById(sysUser.getLoginName());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            long start = student.getAdmissionsTime().getTime();
            long end = System.currentTimeMillis();
            long day = (end - start) / 24 / 60 / 60 / 1000;
            switch ((int) (day / 180 + 1)) {
                case 1:
                    grade = "大一上学期";
                    break;
                case 2:
                    grade = "大一下学期";
                    break;
                case 3:
                    grade = "大二上学期";
                    break;
                case 4:
                    grade = "大二下学期";
                    break;
                case 5:
                    grade = "大三上学期";
                    break;
                case 6:
                    grade = "大三下学期";
                    break;
                case 7:
                    grade = "大四上学期";
                    break;
                default:
                    grade = "大四下学期";
                    break;
            }
            //获取有效成绩数据
            CourseValidGrade cvg = new CourseValidGrade();
            cvg.setStudentNumber(sysUser.getLoginName());
            if(StringUtils.equals(student.getStudentType(),"本科")){
                if ("大四下学期".equals(grade)) {
                    CourseValidGrade courseValidGrade = courseGradeService.selectValidGradeCollect(cvg);
                    if(ObjectUtils.isNotEmpty(courseValidGrade)){
                        content = student.getStudentType() + "：" + sysUser.getUserName() + "目前" + grade + "，总应修学分绩点4分" +
                                "，总实修平均学分绩点：" + courseValidGrade.getAvgCreditGradePoint()
                                +"，毕业状态：" + student.getGraduationStatus();
                    }else{
                        content = student.getStudentType() + "：" + sysUser.getUserName() + "目前" + grade + "，总应修学分绩点4分" +
                                "，总实修平均学分绩点：" + 0
                                +"，毕业状态：" + student.getGraduationStatus();
                    }
                } else {
                    cvg.setStartYear(2021);
                    cvg.setSemester("下");
                    List<CourseValidGrade> courseValidGrades = courseGradeService.selectValidGradeList(cvg);
                    if(courseValidGrades.size() > 0){
                        CourseValidGrade courseValidGrade = courseValidGrades.get(0);
                        content = student.getStudentType() + "：" +sysUser.getUserName() + "目前" + grade + "，本学期应修学分绩点4分" +
                                "，本学期平均学分绩点：" + courseValidGrade.getAvgCreditGradePoint();
                    }else{
                        content = student.getStudentType() + "：" +sysUser.getUserName() + "目前" + grade + "，本学期应修学分绩点4分" +
                                "，本学期平均学分绩点：" + 0;
                    }
                }
            }else{
                if ("大二下学期".equals(grade)) {
                    CourseValidGrade courseValidGrade = courseGradeService.selectValidGradeCollect(cvg);
                    if(ObjectUtils.isNotEmpty(courseValidGrade)){
                        content = student.getStudentType() + "：" + sysUser.getUserName() + "目前" + grade + "，总应修学分绩点2分" +
                                "，总平均学分绩点：" + courseValidGrade.getAvgCreditGradePoint()
                                +"，毕业状态：" + student.getGraduationStatus();
                    }else{
                        content = student.getStudentType() + "：" + sysUser.getUserName() + "目前" + grade + "，总应修学分绩点4分" +
                                "，总实修平均学分绩点：" + 0
                                +"，毕业状态：" + student.getGraduationStatus();
                    }
                } else {
                    cvg.setStartYear(2021);
                    cvg.setSemester("下");
                    List<CourseValidGrade> courseValidGrades = courseGradeService.selectValidGradeList(cvg);
                    if(courseValidGrades.size() > 0){
                        CourseValidGrade courseValidGrade = courseValidGrades.get(0);
                        content = student.getStudentType() + "：" + sysUser.getUserName() + "目前" + grade + "，本学期应修学分绩点2分" +
                                "，本学期平均学分绩点：" + courseValidGrade.getAvgCreditGradePoint();
                    }else{
                        content = student.getStudentType() + "：" +sysUser.getUserName() + "目前" + grade + "，本学期应修学分绩点4分" +
                                "，本学期平均学分绩点：" + 0;
                    }
                }
            }
            mmap.put("content", content);
            mmap.put("gaa", "1");
        }
        return prefix + "/grade";
    }

    @RequiresPermissions("gas:rebuild:view")
    @GetMapping("rebuild")
    public String rebuild(ModelMap mmap) {
        User sysUser = getSysUser();
        if(sysUser.isStudent()){
            Student student = studentService.selectStudentById(sysUser.getLoginName());
            String content = "";
            long start = student.getAdmissionsTime().getTime();
            long end = System.currentTimeMillis();
            long day = (end - start) / 24 / 60 / 60 / 1000;
            int year = (int)day % 180 + 1;
            CourseGrade courseGrade = new CourseGrade();
            courseGrade.setStudentNumber(sysUser.getLoginName());
            courseGrade.setCoueseNature("重修");
            if(year < 8){
                courseGrade.setStartYear(2021);
                courseGrade.setSemester("下");
                List<CourseGrade> list = courseGradeService.selectCourseGradeList(courseGrade);
                List<CourseGrade> jg = list.stream().filter(c -> c.getCourseGrade().compareTo(new BigDecimal(60)) > -1).collect(Collectors.toList());
                List<CourseGrade> bjg = list.stream().filter(c -> c.getCourseGrade().compareTo(new BigDecimal(60)) == -1).collect(Collectors.toList());
                content = "本学期重修通过：" + jg.size() + "个，未通过：" + bjg.size() + "个";
            }else{
                List<CourseGrade> list = courseGradeService.selectCourseGradeList(courseGrade);
                List<CourseGrade> jg = list.stream().filter(c -> c.getCourseGrade().compareTo(new BigDecimal(60)) > -1).collect(Collectors.toList());
                List<CourseGrade> bjg = list.stream().filter(c -> c.getCourseGrade().compareTo(new BigDecimal(60)) == -1).collect(Collectors.toList());
                content = "总重修通过：" + jg.size() + "个，未通过：" + bjg.size() + "个";
            }
            mmap.put("content",content);
            mmap.put("gaa","1");
        }
        return prefix + "/rebuild";
    }

    @RequiresPermissions("gas:grade:valid:view")
    @GetMapping("/valid")
    public String valid() {
        return prefix + "/valid";
    }

    /**
     * 查询课程成绩列表
     */
    @RequiresPermissions("gas:grade:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(CourseGrade courseGrade) {
            startPage();
        User sysUser = getSysUser();
        if(sysUser.isStudent()){
            courseGrade.setStudentNumber(sysUser.getLoginName());
        }
        if(sysUser.isTeacher()){
            courseGrade.setTeacherNumber(sysUser.getLoginName());
        }
        List<CourseGrade> list = courseGradeService.selectCourseGradeList(courseGrade);
//        if(sysUser.isStudent()){
            for (CourseGrade grade : list) {
                User user = userService.selectUserByLoginName(grade.getTeacherNumber());
                Message message = new Message();
                message.setModuleName("grade");
                message.setCourseNumber(grade.getCourseNumber());
                message.setSubmitId(sysUser.getUserId());
                message.setReceiveId(user.getUserId());
                List<Message> messages = messageService.selectMessageList(message);
                grade.setReply(messages.size() > 0);
            }
//        }
        return getDataTable(list);
    }

    /**
     * 查询课程成绩列表
     */
    @RequiresPermissions("gas:grade:valid:list")
    @PostMapping("/valid/list")
    @ResponseBody
    public TableDataInfo validList(CourseValidGrade courseGrade) {
        User sysUser = getSysUser();
        if(sysUser.isStudent()){
            courseGrade.setStudentNumber(sysUser.getLoginName());
        }
        if(sysUser.isTeacher()){
            courseGrade.setMyStudent(sysUser.getLoginName());
        }
        startPage();
        List<CourseValidGrade> list = courseGradeService.selectValidGradeList(courseGrade);
        for (CourseValidGrade grade : list) {
            User user = userService.selectUserByLoginName(grade.getTeacherNumber());
            Message message = new Message();
            message.setModuleName("valid");
            message.setCourseNumber(grade.getCourseType());
            message.setSubmitId(sysUser.getUserId());
            message.setReceiveId(user.getUserId());
            List<Message> messages = messageService.selectMessageList(message);
            grade.setReply(messages.size() > 0);
        }
        return getDataTable(list);
    }


    /**
     * 查询课程成绩列表
     */
    @RequiresPermissions("gas:grade:valid:export")
    @PostMapping("/valid/export")
    @ResponseBody
    public AjaxResult exportValidGrade(CourseValidGrade courseGrade) {
        User sysUser = getSysUser();
        if(sysUser.isStudent()){
            courseGrade.setStudentNumber(sysUser.getLoginName());
        }
        if(sysUser.isTeacher()){
            courseGrade.setMyStudent(sysUser.getLoginName());
        }
        List<CourseValidGrade> list = courseGradeService.selectValidGradeList(courseGrade);
        ExcelUtil<CourseValidGrade> util = new ExcelUtil<>(CourseValidGrade.class);
        return util.exportExcel(list, "gradeValid");
    }

    /**
     * 导出课程成绩列表
     */
    @RequiresPermissions("gas:grade:export")
    @Log(title = "课程成绩", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(CourseGrade courseGrade) {
        User sysUser = getSysUser();
        if(sysUser.isStudent()){
            courseGrade.setStudentNumber(sysUser.getLoginName());
        }
        if(sysUser.isTeacher()){
            courseGrade.setTeacherNumber(sysUser.getLoginName());
        }
        List<CourseGrade> list = courseGradeService.selectCourseGradeList(courseGrade);
        ExcelUtil<CourseGrade> util = new ExcelUtil<>(CourseGrade.class);
        return util.exportExcel(list, "grade");
    }

    /**
     * 新增课程成绩
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存课程成绩
     */
    @RequiresPermissions("gas:grade:add")
    @Log(title = "课程成绩", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(CourseGrade courseGrade) {
        return toAjax(courseGradeService.insertCourseGrade(courseGrade));
    }

    /**
     * 修改课程成绩
     */
    @GetMapping("/edit/{courseGradeId}")
    public String edit(@PathVariable("courseGradeId") Long courseGradeId, ModelMap mmap) {
        CourseGrade courseGrade = courseGradeService.selectCourseGradeById(courseGradeId);
        mmap.put("courseGrade", courseGrade);
        return prefix + "/edit";
    }

    /**
     * 修改保存课程成绩
     */
    @RequiresPermissions("gas:grade:edit")
    @Log(title = "课程成绩", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(CourseGrade courseGrade) {
        return toAjax(courseGradeService.updateCourseGrade(courseGrade));
    }

    /**
     * 删除课程成绩
     */
    @RequiresPermissions("gas:grade:remove")
    @Log(title = "课程成绩", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(courseGradeService.deleteCourseGradeByIds(ids));
    }

    @RequiresPermissions("gas:grade:import")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<CourseGrade> util = new ExcelUtil<>(CourseGrade.class);
        return util.importTemplateExcel("课程成绩");
    }


    @Log(title = "课程成绩" , businessType = BusinessType.IMPORT)
    @RequiresPermissions("gas:grade:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<CourseGrade> util = new ExcelUtil<>(CourseGrade.class);
        List<CourseGrade> courseGradeList = util.importExcel(file.getInputStream());
        //数据校验
        for (CourseGrade courseGrade : courseGradeList) {
            courseGrade.setCreateBy(getLoginName());
            courseGrade.setCreateTime(DateUtils.getNowDate());
            String check = courseGrade.check(courseGrade);
            if(StringUtils.isNotEmpty(check)){
                return error(check);
            }
        }
        String message = courseGradeService.importTeacher(courseGradeList);
        return AjaxResult.success(message);
    }
}
